import subprocess
from enum import Enum

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox


class JarPath(Enum):
    setPath = "./SetPathConfig.jar"
    simulationPath = "./Simulation.jar"


class EmulatorLaunchTool(QtWidgets.QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("Emulator Launch Tool")

        self.button_draw_path = QtWidgets.QPushButton()
        self.button_draw_path.setText("画路径")

        self.button_track_simulation = QtWidgets.QPushButton()
        self.button_track_simulation.setText("航迹模拟")

        self.button_set_aerodrome = QtWidgets.QPushButton()
        self.button_set_aerodrome.setText("设置机场信息")

        self.main_layout = QtWidgets.QHBoxLayout()

        self.ui_init()
        self.ui_layout()
        self.ui_connect()

    def ui_init(self):
        """

        @return:
        """
        if not self.check_java_environment():
            QMessageBox.critical(
                self,
                '没有Java环境',
                '未找到 Java 环境。请安装 Java 以运行此应用程序。'
            )
        else:
            QMessageBox.information(
                self,
                'Java环境检测',
                'Java 环境检测通过。'
            )

    def ui_layout(self):
        """

        @return:
        """
        self.main_layout.addWidget(self.button_draw_path)
        self.main_layout.addWidget(self.button_track_simulation)
        self.main_layout.addWidget(self.button_set_aerodrome)
        self.setLayout(self.main_layout)

    def ui_connect(self):
        """

        @return:
        """
        self.button_draw_path.clicked.connect(self.open_draw_path)
        self.button_track_simulation.clicked.connect(self.open_simulation)

    def open_draw_path(self):
        """
        打开设置路径窗口
        @return:
        """
        self.call_java_jar(JarPath.setPath)

    def open_simulation(self):
        """
        打开航迹模拟窗口
        @return:
        """
        self.call_java_jar(JarPath.simulationPath)

    @staticmethod
    def check_java_environment():
        try:
            subprocess.check_output(['java', '-version'], stderr=subprocess.STDOUT)
            return True
        except subprocess.CalledProcessError:
            return False

    @staticmethod
    def call_java_jar(jar_path: JarPath):
        java_cmd = f'java -jar {jar_path.value}'
        print(f"执行： {java_cmd}")
        process = subprocess.Popen(java_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        output, error = process.communicate()
        return output.decode(), error.decode()


if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    mainWindow = EmulatorLaunchTool()
    mainWindow.show()
    sys.exit(app.exec_())
